const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const config = require('../config')

router.prefix('/articles')

router.post("/", async function(ctx, next) {

})

router.put("/add", async function(ctx, next) {
  var user = ctx.currentUser
  var data = ctx.request.body
  await ctx.connection.query({
    sql: 'insert into article(title,content,userid,publishDate) values(?,?,?,?)',
    values: [data.A_title,data.A_content,user.id,new Date()]
  })
    .then((resp) => ctx.body = resp)
})

router.get("/", async function(ctx, next) {
  await ctx.connection.query({
    sql: 'select * from article'
  })
    .then((resp) => ctx.body = resp)
})

router.get("/lastest/:num", async function(ctx, next) {
  var num = ctx.params.num;
  await ctx.connection.query({
    sql: 'SELECT * FROM article ORDER BY id desc limit ?',
    values: [parseInt(num)]
  })
    .then((resp) => ctx.body = resp)
})

router.get("/:id", async function(ctx, next) {
    var id = ctx.params.id;
    await ctx.connection.query({
      sql:'select * from article where id = ?',
      values:[id]
    }).then((resp) => ctx.body = resp)
})

router.put("/delete/:id", async function(ctx, next) {
    var id = ctx.params.id;
    var user = ctx.currentUser;
    await ctx.connection.query({
      sql:'delete from article where id = ? and userid = ?',
      values:[id,user.id]
    }).then((resp) => {
      if (resp.affectedRows==0) {
          ctx.body = {error:true,message:'删除失败，非法权限'}
          return;
      }
      ctx.body = {error:false,message:'删除成功'}
    })

})



module.exports = router
//create table if not exists article(id int auto_increment primary key,title varchar(255) not null,content text,userid int,foreign key(userid) references user(id),publishDate DATETIME not null default '2015-01-01');
